// 接口配置
let baseUrl = 'http://接口域名/'
const uploadPresignedUrl = '获取上传签名/get-upload-token'
const batchUploadPresignedUrl = '批量获取上传签名/get-batch-upload-token'
const getFileUrl = '获取文件下载地址/get-file-url'
const postBatchFileUrl = '批量获取文件下载地址/post-batch-file-url'
const headerAuthName = 'token'

// 接口配置/京师书法小程序
// import APIConfig from '../../config/api.js'
// let baseUrl = (APIConfig.baseUrl || '') + '/sf-base/'
// const uploadPresignedUrl = 'oss/uploadSign'
// const batchUploadPresignedUrl = 'oss/get-batch-upload-token'
// const getFileUrl = 'oss/get-file-url'
// const postBatchFileUrl = 'oss/post-batch-file-url'
// const headerAuthName = 'token'

export default {
  /**
   * 上传文件到 oss
   * @param {Object} params 包含 file 和 isShare 参数
   */
  upload (params) {
    let file = params.file;
    let isShare = !!params.isShare;
    if (!file) { return Promise.reject('参数不能为空！') }
    if (!file.name) { params.fileName = file.name = (file.tempFilePath || file.url).split('/').pop(); }
    let _this = this;
    return _this.getUploadKey(file, isShare)
      .then((data) => {
        const fileName = data.fileName
        const signInfo = JSON.parse(data.signInfo)
        wx.uploadFile({
          url: signInfo.host,
          filePath: file.url || file.tempFilePath || file,
          name: 'file',
          formData: {
            name: file.url,
            key: signInfo.dir + fileName,       // 存储在oss的文件路径
            OSSAccessKeyId: signInfo.accessid,  // accessKeyId
            policy: signInfo.policy,            // policy
            signature: signInfo.signature,      // 签名
            callback: signInfo.callback,        // callback
            success_action_status: 200,         // 成功后返回的操作码
          },
          success(res) {
            let data = (res || {}).data
            if (typeof data === 'string') {
              data = JSON.parse(data)
            }
            resolve(data)
          },
          fail (err) {
            reject(err)
          }
        })
      })
      .catch((error) => {
        return Promise.reject(error);
      })
  },
  // 从服务端获取上传签名信息-单个
  getUploadKey(file, isShare) {
    const reqUrl = baseUrl + uploadPresignedUrl
    const originalName = file.url.split('/').pop()
    return new Promise((resolve, reject) => {
      wx.request({
        url: reqUrl,
        method: 'GET',
        data: {
          originalName,
          share: isShare,
          platform: 'file_oss'
        },
        header: {
          [headerAuthName]: wx.getStorageSync(headerAuthName),
          'Content-Type': 'application/json'
        },
        success(res) {
          if (res.statusCode === 200 && res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject(res.data.message || '获取上传签名信息失败！');
          }
        },
        fail(err) {
          reject(err)
        }
      })
    })
  },
  // 获取文件下载地址
  getFileUrl (fileName, isShare = false) {
    const reqUrl = baseUrl + getFileUrl
    if (!fileName) { return Promise.reject('参数不能为空！') }
    return new Promise((resolve, reject) => {
      wx.request({
        url: reqUrl,
        method: 'GET',
        data: {
          fileName: fileName,
          flag: !!isShare,
          expiration: 86400000
        },
        header: {
          [headerAuthName]: wx.getStorageSync(headerAuthName),
          'Content-Type': 'application/json'
        },
        success(res) {
          if (res.statusCode === 200 && res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject(res.data.message || '获取文件下载地址失败！');
          }
        },
        fail(err) {
          reject(err)
        }
      })
    })
  },
  // 批量获取文件下载地址
  getBatchFileUrl(fileNames) {
    const reqUrl = baseUrl + postBatchFileUrl
    if (fileNames.length === 0) { return Promise.resolve([]) }
    return new Promise((resolve, reject) => {
      wx.request({
        url: reqUrl,
        method: 'POST',
        data: {
          fileNames: fileNames,
          expiration: 86400000
        },
        header: {
          [headerAuthName]: wx.getStorageSync(headerAuthName),
          'Content-Type': 'application/json'
        },
        success(res) {
          if (res.statusCode === 200 && res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject(res.data.message || '获取文件下载地址失败！');
          }
        },
        fail(err) {
          reject(err);
        }
      })
    })
  },
}
